<template>
  <view class="container">
    <view class="header">
      <text class="title">欢迎注册学习助手</text>
      <text class="subtitle">开启您的学习之旅</text>
    </view>
    
    <view class="form-container">
      <view class="form-group">
        <text class="label">手机号/邮箱</text>
        <input 
          class="input" 
          type="text" 
          placeholder="请输入手机号/邮箱" 
          v-model="registerForm.account"
        />
      </view>
      
      <view class="form-group">
        <text class="label">密码</text>
        <view class="password-group">
          <input 
            class="input password-input" 
            :type="showPassword ? 'text' : 'password'" 
            placeholder="请输入密码" 
            v-model="registerForm.password"
          />
          <view class="eye-icon" @click="togglePasswordVisibility">
            <text>{{ showPassword ? '👁️' : '👁️‍🗨️' }}</text>
          </view>
        </view>
        <text class="password-hint">密码长度至少6位</text>
      </view>
      
      <view class="form-group">
        <text class="label">验证码</text>
        <view class="verification-code-group">
          <input 
            class="input verification-code-input" 
            type="text" 
            placeholder="请输入验证码" 
            v-model="registerForm.verificationCode"
          />
          <button class="send-code-btn" type="button" :disabled="countingDown" @click="sendVerificationCode">
            {{ countingDown ? (countdown + '秒后重发') : '发送验证码' }}
          </button>
        </view>
      </view>
      
      <view class="agreement-group">
        <checkbox-group @change="onAgreeGroupChange">
          <label>
            <checkbox class="checkbox" value="agree" :checked="agreeToTerms"></checkbox>
          </label>
        </checkbox-group>
        <text class="agreement-text">
          我已阅读并同意
          <text class="link" @click="showTerms">《服务条款》</text>
          和
          <text class="link" @click="showPrivacy">《隐私政策》</text>
        </text>
      </view>
      
      <Button 
        class="register-btn" 
        type="primary" 
        text="注册并登录" 
        :loading="loading"
        @click="handleRegister"
      />
      
      <view class="login-link">
        <text class="text">已有账户？</text>
        <text class="link" @click="goToLogin">立即登录</text>
      </view>
    </view>
  </view>
</template>

<script>
import { setStorage } from '../../utils/storage.js';
import { services } from '../../api/index.js';
import { getCode } from '../../api/code.js';
import { registerEmail } from '../../api/register.js';
const userAPI = services.user;

export default {
  data() {
    return {
      registerForm: {
        account: '',
        password: '',
        verificationCode: ''
      },
      loading: false,
      showPassword: false,
      agreeToTerms: false,
      countingDown: false,
      countdown: 60,
      codeTimer: null
    };
  },
  onUnload() {
    if (this.codeTimer) {
      clearInterval(this.codeTimer);
      this.codeTimer = null;
    }
  },
  methods: {
    togglePasswordVisibility() {
      this.showPassword = !this.showPassword;
    },
    
    onAgreeGroupChange(e) {
      console.log('[register] onAgreeGroupChange event:', e);
      const arr = (e && e.detail && Array.isArray(e.detail.value)) ? e.detail.value : [];
      this.agreeToTerms = arr.includes('agree');
      console.log('[register] agreeToTerms ->', this.agreeToTerms);
    },
    
    async sendVerificationCode() {
      console.log('[register] sendVerificationCode click');
      if (!this.registerForm.account) {
        uni.showToast({
          title: '请输入手机号/邮箱',
          icon: 'none'
        });
        return;
      }
      
      // 验证手机号/邮箱格式
      if (!this.isValidAccount(this.registerForm.account)) {
        uni.showToast({
          title: '请输入有效的手机号或邮箱',
          icon: 'none'
        });
        return;
      }
      
      try {
        if (this.codeTimer) {
          clearInterval(this.codeTimer);
          this.codeTimer = null;
        }
        // 1 手机 2 邮箱
        const isPhone = /^1[3-9]\d{9}$/.test(this.registerForm.account);
        const payload = isPhone
          ? { type: 1, areaCode: '86', phone: this.registerForm.account }
          : { type: 2, email: this.registerForm.account };
        console.log('[register] getCode payload ->', payload);
        const resp = await getCode(payload);
        console.log('[register] getCode resp ->', resp);
        // 开始倒计时
        this.countingDown = true;
        this.countdown = 60;
        console.log('[register] sendVerificationCode success, start countdown');
        this.codeTimer = setInterval(() => {
          this.countdown--;
          console.log('[register] countdown ->', this.countdown);
          if (this.countdown <= 0) {
            clearInterval(this.codeTimer);
            this.codeTimer = null;
            this.countingDown = false;
          }
        }, 1000);
        uni.showToast({ title: '验证码已发送', icon: 'success' });
      } catch (e) {
        console.error('[register] sendVerificationCode error ->', e);
        this.countingDown = false;
        uni.showToast({ title: e?.data?.msg || '发送验证码失败', icon: 'none' });
      }
    },
    
    isValidAccount(account) {
      // 简单的手机号或邮箱格式验证
      const phoneRegex = /^1[3-9]\d{9}$/;
      const emailRegex = /^[\w-]+(\.[\w-]+)*@[\w-]+(\.[\w-]+)+$/;
      return phoneRegex.test(account) || emailRegex.test(account);
    },
    
    showTerms() {
      // 显示服务条款
      uni.showToast({
        title: '服务条款页面待实现',
        icon: 'none'
      });
    },
    
    showPrivacy() {
      // 显示隐私政策
      uni.showToast({
        title: '隐私政策页面待实现',
        icon: 'none'
      });
    },
    
    async handleRegister() {
      console.log('[register] handleRegister submit', { form: this.registerForm, agreeToTerms: this.agreeToTerms });
      if (!this.registerForm.account) {
        uni.showToast({
          title: '请输入手机号/邮箱',
          icon: 'none'
        });
        return;
      }
      
      if (!this.isValidAccount(this.registerForm.account)) {
        uni.showToast({
          title: '请输入有效的手机号或邮箱',
          icon: 'none'
        });
        return;
      }
      
      if (!this.registerForm.password) {
        uni.showToast({
          title: '请输入密码',
          icon: 'none'
        });
        return;
      }
      
      if (this.registerForm.password.length < 6) {
        uni.showToast({
          title: '密码长度至少6位',
          icon: 'none'
        });
        return;
      }
      
      if (!this.registerForm.verificationCode) {
        uni.showToast({
          title: '请输入验证码',
          icon: 'none'
        });
        return;
      }
      
      if (!this.agreeToTerms) {
        uni.showToast({
          title: '请阅读并同意服务条款和隐私政策',
          icon: 'none'
        });
        return;
      }
      
      try {
        this.loading = true;
        // 依据账号类型选择接口
        let resp;
        if (/^1[3-9]\d{9}$/.test(this.registerForm.account)) {
          resp = await userAPI.register({
            areaCode: '86',
            phone: this.registerForm.account,
            password: this.registerForm.password,
            code: this.registerForm.verificationCode,
            appType: 2,
            mapType: 1,
            Language: 'zh-CN'
          });
        } else {
          resp = await registerEmail({
            email: this.registerForm.account,
            password: this.registerForm.password,
            code: this.registerForm.verificationCode,
            appType: 2,
            mapType: 1,
            Language: 'zh-CN'
          });
        }
        uni.showToast({ title: '注册成功', icon: 'success' });
        // 注册成功后建议直接调用账号密码登录或跳到登录页
        setTimeout(() => {
          uni.navigateTo({ url: '/pages/auth/login' });
        }, 800);
      } finally {
        this.loading = false;
      }
    },
    
    goToLogin() {
      uni.navigateTo({
        url: '/pages/auth/login'
      });
    }
  }
};
</script>

<style lang="scss" scoped>
.container {
  padding: $spacing-xl;
  background-color: $background-color;
  min-height: 100vh;
  display: flex;
  flex-direction: column;
  align-items: center;
  padding-top: 100rpx;
  box-sizing: border-box;
}

.header {
  text-align: center;
  margin-bottom: 60rpx;
}

.title {
  font-size: 48rpx;
  font-weight: bold;
  color: $text-primary;
  display: block;
  margin-bottom: 16rpx;
}

.subtitle {
  font-size: 28rpx;
  color: $text-secondary;
}

.form-container {
  width: 100%;
  max-width: 600rpx;
}

.form-group {
  margin-bottom: 32rpx;
}

.label {
  display: block;
  font-size: 28rpx;
  color: $text-primary;
  margin-bottom: 12rpx;
}

.input {
  width: 100%;
  height: 96rpx;
  padding: 0 32rpx;
  border: 1rpx solid $text-tertiary;
  border-radius: 16rpx;
  font-size: 28rpx;
  box-sizing: border-box;
  background-color: #ffffff;
}

.password-group {
  position: relative;
}

.password-input {
  padding-right: 80rpx;
}

.eye-icon {
  position: absolute;
  right: 32rpx;
  top: 50%;
  transform: translateY(-50%);
  font-size: 40rpx;
}

.password-hint {
  font-size: 24rpx;
  color: $text-tertiary;
  margin-top: 8rpx;
  display: block;
}

.verification-code-group {
  display: flex;
  align-items: center;
  gap: 20rpx;
}

.verification-code-input {
  flex: 1;
}

.send-code-btn {
  height: 96rpx;
  padding: 0 32rpx;
  border: 1rpx solid $primary-color;
  border-radius: 16rpx;
  background-color: #ffffff;
  color: $primary-color;
  font-size: 28rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  min-width: 200rpx;
}

.send-code-btn:disabled {
  opacity: 0.6;
  border-color: $text-tertiary;
  color: $text-tertiary;
}

.agreement-group {
  display: flex;
  align-items: center;
  margin-bottom: 40rpx;
}

.checkbox {
  transform: scale(0.8);
  margin-right: 12rpx;
}

.agreement-text {
  font-size: 24rpx;
  color: $text-secondary;
  flex: 1;
}

.link {
  color: $primary-color;
  font-size: 24rpx;
  
  &:active {
    opacity: 0.8;
  }
}

.register-btn {
  width: 100%;
  height: 46rpx;
  line-height: 46rpx;
  border-radius: 16rpx;
  font-size: 32rpx;
  margin-bottom: 40rpx;
}

.login-link {
  text-align: center;
  margin-top: 20rpx;
}

.login-link .text {
  font-size: 28rpx;
  color: $text-secondary;
}

.login-link .link {
  font-size: 28rpx;
}
</style>